/**
 * Created by sa on 2016/9/22.
 * casperjs sougou.js
 */
var fs = require('fs');
var casper = require('casper').create({
  clientScripts: [
    'script/jquery-1.12.4.js',      // These two scripts will be injected in remote
    'script/underscore-min.js'      // These two scripts will be injected in remote
  ],
  pageSettings: {
    loadImages: true,
    loadPlugins: false,
    userAgent: 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/34.0.1847.137 Safari/537.36 LBBROWSER'
  },
  //logLevel: "debug",//日志等级
  logLevel: "error",//日志等级
  verbose: true,    // 记录日志到控制台
  timeout: 60000,//60秒超时，退出
  onWaitTimeout:function(){
    this.echo('-----output-----timeout-----output end-----','Info');
  }
});

var ip = getIP()

var head = {
  method: 'get',
  headers: {
    "X-Forwarded-For": ip,
    "X-Real-IP" : ip,
    "HTTP_CLIENT_IP" : ip
  },
  encoding: 'utf8'
}

//console.log(head.headers['X-Forwarded-For']);
//排除不相关的请求，加快页面加载进度
/**
casper.on('resource.requested', function (requestData, request) {
  if (requestData.url.indexOf('sogou.com') > 0) {
    this.echo("==============>page.resource.requested"+requestData.url);
    this.echo("==============>page.resource.requested"+request);
  }
});
**/

casper.start();

var src = "";

casper.viewport(1024, 1024);

casper.thenOpen('http://www.kaikouyingyu.cn/sougou.html',
  head,
  function () {
    this.page.switchToChildFrame(0); // 页面包含 iFrame
    src = this.getPageContent();
    //fs.write("sougou/1.html", src, 'w');  // 保存 iFrame 里的内容
  })



casper.then(function () {

  src = pp(src);
  if (src) {

    console.log("mouseEvent");
    this.mouse.click(100, 15);

    console.log("获取到href")
    fs.write("sougou/30/1sougou.txt",ip + "\n" + src + "\n", 'a+');
    openAdUrl();
  }
});


function openAdUrl() {
  //console.log("casperObj start")
  casper.open(src, head, function () {
    this.scrollToBottom();
  })
}
/****/

//保存追踪图片
casper.then(function () {

  var pathP = 'sougou/30/';
  if(src){
    pathP += "ok_";
  }else{
    pathP += "no_";
  }
  pathP += new Date().valueOf() + '.png'

/*  this.captureSelector(pathP, 'body' , {
    top: 0,
    left: 0,
    width: 500,
    height: 500
  });*/

  this.capture(pathP, {
    top: 0,
    left: 0,
    width: 500,
    height: 500
  });
  console.log("tag save img ok");
});

casper.run(function () {
  //this.echo(this.getCurrentUrl());
  this.exit();
});

function getIP(){
  var ip = Math.floor(Math.random()*255+1)
    + '.'
    + Math.floor(Math.random()*255+1)
    + '.'
    + Math.floor(Math.random()*255+1)
    + '.'
    + Math.floor(Math.random()*255+1);
  return ip;
}

function pp(txt){

  var re=/url : "([a-zA-z]+:\/\/[^\s]*)",/g;
  var arr=[];
  var href = null;
  while(re.exec(txt)!=null)
  {
    href = RegExp.$1 ;
    if(href.indexOf("www.sogou.com") > 0){
      arr.push(href);//如果是RegExp.$1那么匹配的就是href里的属性了!
      //fs.write("sougou/sougou.txt", href + "\n" , 'a+');
    }
  }
  var id = Math.floor(Math.random()*15+1)
  if(id % 3 == 0){
  //if(true){
    //var index = Math.floor(Math.random()*12+1)
    //href = arr[index];
    href = arr[0];
  }else{
    href = null;
  }
  return href;
}
